import java.io.IOException;

import aws.EC2;

import pjaws.*;
import pjaws.paw.*;

/**
 * 
 * PJAWS Example Application
 * 
 * Simple two node topology.
 * 
 * Server sends data set to client, client returns minimum of data set.
 * 
 * @author Zachary Cancio
 * 
 */

public class ExamplePjaws extends Pjaws {
	public static final int SERVER = 13;
	public static final int CLIENT1 = 14;

	// ---------CONTSRUCTORS-----------//
	public ExamplePjaws(String[] args) {
		super();

		// 2. prepare ec2 if root
		if (args[0].equals("-r")) {
			String currDir = System.getProperty("user.dir");
			String key = currDir + "/pk-PEXNMTQQYNTJAPRC5H62B3KO7NO55QOV.pem";
			String cert = currDir
					+ "/cert-PEXNMTQQYNTJAPRC5H62B3KO7NO55QOV.pem";
			setEC2(new EC2(key, cert));
		}
		// 3. add paws
		// unfortunately every paw needs info about every other node... v2
		// should fix this.
		addPaw(SERVER, new PawServer());
		addPaw(CLIENT1, new PawClient1());

	}

	// ---------DEFINE PaWs----------//

	class PawClient1 extends Paw {
		public PawClient1() {
			// set PaW Id as client1
			this.setPawId(CLIENT1);
			// Add socket connection(s)
			// Need to know which PaWs to connect to before running, hence why
			// not in run...
			PawSocket ps = new PawSocket(SERVER);
			this.addPawSocket(ps);
		}

		@Override
		public void run() {
			int[] set;
			System.out.println("I'm CLIENT1!");
			try {

				set = (int[]) receivePawMessage(SERVER, 1);
				System.out.println("RECEIVED: " + set);
				int max = set[0];
				for (int i : set) {
					if (i > max) {
						max = i;
					}
				}
				sendPawMessage(max, SERVER, 2);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	class PawServer extends Paw {

		public PawServer() {
			// set PaW Id as Server
			this.setPawId(SERVER);

			// add socket connections
			PawSocket ps = new PawSocket(CLIENT1);
			this.addPawSocket(ps);
		}

		@Override
		public void run() {
			// initialize data
			int setlen = 2000000; // a 1 million integers!
			int[] set1 = new int[setlen];
			for (int i = 0; i < setlen; i++) {
				set1[i] = i;
			}

			int overall_max = 0;

			try {
				System.out.println("I'm SERVER!");
				// send set1 to client
				sendPawMessage(set1, CLIENT1, 1);
				System.out.println("SENT: " + set1);
				// receive max1 from client
				int max1 = (Integer) receivePawMessage(CLIENT1, 2);
				System.out.println("The Client 1 Max is: " + max1);
				// overall_max = max1;
				System.out.println("OVERALL_MAX is: " + overall_max);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		ExamplePjaws pjaws = new ExamplePjaws(args);
		pjaws.run(args);
	}

}
